package cn.woochen.mvvmframe.config.ext

import cn.woochen.mvvmframe.config.BaseActivity
import cn.woochen.mvvmframe.config.BaseDialogFragment
import cn.woochen.mvvmframe.config.BaseFragment
import cn.woochen.mvvmframe.config.status.CustomException
import cn.woochen.mvvmframe.config.status.ResultState
import cn.woochen.mvvmframe.config.BaseViewGroup


fun <T> BaseFragment<*, *>.parseState(resultState: ResultState<T>, onSuccess: (T?, String, String,Any) -> Unit, onError: ((CustomException,Any) -> Unit)? = null) {
    when (resultState) {
        is ResultState.Success -> {
            onSuccess(resultState.data, resultState.code, resultState.message,resultState.extParams)
        }
        is ResultState.Error -> {
            val e = resultState.error
            onError?.run { this(e,resultState.extParams) }
        }
    }
}

fun <T> BaseDialogFragment<*, *>.parseState(resultState: ResultState<T>, onSuccess: (T?, String, String,Any) -> Unit, onError: ((CustomException,Any) -> Unit)? = null) {
    when (resultState) {
        is ResultState.Success -> {
            onSuccess(resultState.data, resultState.code, resultState.message,resultState.extParams)
        }
        is ResultState.Error -> {
            val e = resultState.error
            onError?.run { this(e,resultState.extParams) }
        }
    }
}

/**
 * 显示页面状态，这里有个技巧，成功回调在第一个，其后两个带默认值的回调可省
 * @param resultState 接口返回值
 * @param onSuccess 成功回调
 * @param onError 失败回调
 */
fun <T> BaseActivity<*, *>.parseState(resultState: ResultState<T>, onSuccess: (T?, String, String,Any) -> Unit, onError: ((CustomException,Any) -> Unit)? = null) {
    when (resultState) {
        is ResultState.Success -> {
            onSuccess(resultState.data, resultState.code, resultState.message,resultState.extParams)
        }
        is ResultState.Error -> {
            val e = resultState.error
            onError?.run { this(e,resultState.extParams) }
        }
    }
}

/**
 * @param resultState 接口返回值
 * @param onSuccess 成功回调
 * @param onError 失败回调
 */
fun <T> BaseViewGroup<*>.parseState(resultState: ResultState<T>, onSuccess: (T?, String, String,Any) -> Unit, onError: ((CustomException,Any) -> Unit)? = null) {
    when (resultState) {
        is ResultState.Success -> {
            onSuccess(resultState.data, resultState.code, resultState.message,resultState.extParams)
        }
        is ResultState.Error -> {
            val e = resultState.error
            onError?.run { this(e,resultState.extParams) }
        }
    }
}

